<template>
    <el-card class="box-card" shadow="never">
        <div class="title">任务分配机制</div>
        <el-divider class="line" border-style="double" />
        <el-form
            ref="step2Form"
            :model="step2Data"
            :rules="step2Rules"
            label-width="80px"
            label-postion="right"
            :disabled="step2Diabled">
            <el-form-item label="执行员工" prop="work_user_type" :class="{ mb0: step2Data.work_user_type == 2 }">
                <el-radio-group v-model="step2Data.work_user_type">
                    <el-radio :label="1" value="1">全部员工</el-radio>
                    <el-radio :label="2" value="2">指定员工</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item
                v-if="step2Data.work_user_type == 2"
                class="notShow_formItem_required"
                label=" "
                prop="work_user_ids">
                <div>
                    <el-button type="primary" @click="openDepart">选择员工</el-button>
                </div>
                <div v-if="creators.length > 0" class="user_list">
                    <el-tag
                        v-for="tag in creators"
                        :key="tag.id"
                        class="user_item_tag"
                        :closable="!step2Diabled"
                        type="info"
                        @close="removeDepart(tag.id)">
                        <img class="tag_icon" src="@/assets/image/LiveCode/people_icon.png" alt="" />
                        {{ tag.name }}
                    </el-tag>
                </div>
            </el-form-item>
            <!-- 外呼对象 -->
            <el-form-item
                v-if="task_type != 3"
                :label="`${task_type == 1 ? '外呼' : '拜访'}对象`"
                prop="execution_mode">
                <el-radio-group v-model="step2Data.execution_mode" @change="changeMode">
                    <el-radio :label="1">{{ `指定${task_type == 1 ? '外呼' : '拜访'}对象` }}</el-radio>
                    <el-radio :label="2">员工录入</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 对象类型 -->
            <el-form-item v-if="step2Data.execution_mode == 1" label="对象类型" prop="object_type">
                <el-radio-group v-model="step2Data.object_type" @change="changeType">
                    <el-radio :label="1">线索</el-radio>
                    <el-radio :label="2">客户</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 线索 -->
            <template v-if="step2Data.execution_mode == 1">
                <template v-if="step2Data.object_type == 1">
                    <el-form-item class="clues_box" label="" prop="clue_number">
                        <el-tabs v-model="step2Data.object_source" class="demo-tabs" @tab-change="changeSource">
                            <el-tab-pane label="选择线索" :name="1" :disabled="step2Diabled">
                                <el-button @click="openClues">选择线索</el-button>
                                <div class="cust_number">
                                    已选择线索<span>{{ numFormat(step2Data.clue_number) }}</span
                                    >个
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="线索导入" :name="2" :disabled="step2Diabled">
                                <div class="contract_code">
                                    <el-dropdown>
                                        <el-button
                                            >导入文件<el-icon class="el-icon--right"><arrow-down /></el-icon
                                        ></el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="1">
                                                    <UploadFile
                                                        ref="UploadFileRef"
                                                        :type-data="{
                                                            type: 1,
                                                            object_type: step2Data.object_type,
                                                            name: '个人线索文件'
                                                        }"
                                                        @submit="getFile" />
                                                </el-dropdown-item>
                                                <el-dropdown-item command="2">
                                                    <UploadFile
                                                        ref="UploadFileRef2"
                                                        :type-data="{
                                                            type: 2,
                                                            object_type: step2Data.object_type,
                                                            name: '企业线索文件'
                                                        }"
                                                        @submit="getFile" />
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                    <el-dropdown class="btn" @command="onDownload">
                                        <el-button class="btn_down"
                                            >下载模板 <el-icon class="el-icon--right"><arrow-down /></el-icon
                                        ></el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="3">个人线索模板</el-dropdown-item>
                                                <el-dropdown-item command="4">企业线索模板</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                                <div v-if="step2Data.import_id" class="contract_show">
                                    <div class="contract_show_left">
                                        <img class="contract_show_img" src="/static/file/xls.png" alt="" />
                                        {{ fileInfo.name }}
                                    </div>
                                    <el-icon class="contract_show_delete" @click="onDeleteFile">
                                        <DeleteFilled />
                                    </el-icon>
                                </div>
                                <div class="cust_number">
                                    包含线索<span>{{ numFormat(step2Data.clue_number) }}</span
                                    >个
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </el-form-item>
                </template>
                <!-- 客户 -->
                <template v-else>
                    <el-form-item class="clues_box" label="" prop="cust_number">
                        <el-tabs v-model="step2Data.object_source" class="demo-tabs" @tab-change="changeSource">
                            <el-tab-pane label="选择客户" :name="1" :disabled="step2Diabled">
                                <el-button @click="openCustomer">选择客户</el-button>
                                <div class="cust_number">
                                    已选择客户<span>{{ numFormat(step2Data.cust_number) }}</span
                                    >个
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="客户导入" :name="2" :disabled="step2Diabled">
                                <div class="contract_code">
                                    <el-dropdown>
                                        <el-button
                                            >导入文件 <el-icon class="el-icon--right"><arrow-down /></el-icon
                                        ></el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="1">
                                                    <UploadFile
                                                        ref="UploadFileRef"
                                                        :type-data="{
                                                            type: 1,
                                                            object_type: step2Data.object_type,
                                                            name: '个人客户文件'
                                                        }"
                                                        @submit="getFile" />
                                                </el-dropdown-item>
                                                <el-dropdown-item command="2">
                                                    <UploadFile
                                                        ref="UploadFileRef2"
                                                        :type-data="{
                                                            type: 2,
                                                            object_type: step2Data.object_type,
                                                            name: '企业客户文件'
                                                        }"
                                                        @submit="getFile" />
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                    <el-dropdown class="btn" @command="onDownload">
                                        <el-button class="btn_down"
                                            >下载模板 <el-icon class="el-icon--right"><arrow-down /></el-icon
                                        ></el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="1">个人客户模板</el-dropdown-item>
                                                <el-dropdown-item command="2">企业客户模板</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                                <div v-if="step2Data.import_id" class="contract_show">
                                    <div class="contract_show_left">
                                        <img class="contract_show_img" src="/static/file/xls.png" alt="" />
                                        {{ fileInfo.name }}
                                    </div>
                                    <el-icon class="contract_show_delete" @click="onDeleteFile">
                                        <DeleteFilled />
                                    </el-icon>
                                </div>
                                <div class="cust_number">
                                    包含客户<span>{{ numFormat(step2Data.cust_number) }}</span
                                    >个
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </el-form-item>
                </template>
            </template>
            <!-- 外呼对象 -->
            <template v-if="step2Data.execution_mode == 2">
                <el-form-item label="录入类型" prop="object_type">
                    <el-radio-group v-model="step2Data.object_type">
                        <el-radio :label="1">线索</el-radio>
                        <el-radio :label="2">客户</el-radio>
                    </el-radio-group>
                </el-form-item>
            </template>
            <!-- 录入规则 -->
            <template v-if="step2Data.execution_mode == 2">
                <el-form-item label="录入规则" prop="checkList">
                    <el-checkbox-group v-model="step2Data.checkList" @change="changeCheckbox">
                        <el-checkbox class="rule_checkbox" label="entry_day_switch">
                            每个员工每日至少录入
                            <el-input
                                v-model="step2Data.entry_rule.entry_day_num"
                                type="number"
                                step="1"
                                min="1"
                                class="mar_w"
                                @input="inputNum" />
                            个客户/线索
                        </el-checkbox>
                        <el-checkbox label="entry_user_switch">
                            每个员工至少录入
                            <el-input
                                v-model="step2Data.entry_rule.entry_user_num"
                                type="number"
                                step="1"
                                min="1"
                                class="mar_w"
                                @input="inputNum" />
                            个客户/线索
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </template>
            <!-- 分配规则 -->
            <template v-if="step2Data.execution_mode == 1">
                <el-form-item label="分配规则" prop="cycle_rule.assign_type">
                    <el-radio-group v-model="step2Data.cycle_rule.assign_type" @change="changeAssignType">
                        <el-radio :label="1" value="1">一次分配</el-radio>
                        <el-radio :label="2" value="2">周期分配</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 周期分配 -->
                <template v-if="step2Data.cycle_rule.assign_type == 2">
                    <el-form-item label="周期频次" prop="cycle_rule.cycle_unit">
                        每
                        <el-select
                            v-model="step2Data.cycle_rule.cycle_unit"
                            placeholder="日"
                            style="width: 90px; margin: 0 5px"
                            @change="cycleUnit">
                            <el-option label="日" :value="1" />
                            <el-option label="周" :value="2" />
                            <el-option label="月" :value="3" />
                        </el-select>
                        <template v-if="step2Data.cycle_rule.cycle_unit != 1">
                            <el-select
                                v-model="step2Data.cycle_rule.cycle_date"
                                placeholder="选择日期"
                                style="width: 90px; margin: 0 5px">
                                <!-- 周 -->
                                <template v-if="step2Data.cycle_rule.cycle_unit == 2">
                                    <el-option
                                        v-for="(item, index) in week"
                                        :key="index"
                                        :label="item"
                                        :value="index + 1" />
                                </template>
                                <!-- 月 -->
                                <template v-else>
                                    <el-option v-for="item in 31" :key="item" :label="`${item}号`" :value="item" />
                                </template>
                            </el-select>
                        </template>
                        <el-time-select
                            v-model="step2Data.cycle_rule.cycle_time"
                            style="width: 180px"
                            start="00:00"
                            step="00:30"
                            end="23:59"
                            placeholder="选择时间" />
                        分配
                        <el-input
                            v-model="step2Data.cycle_rule.cycle_num"
                            type="number"
                            step="1"
                            min="1"
                            class="mar_w"
                            @input="inputNum" />个
                        {{ step2Data.object_type == 1 ? '线索' : '客户' }}
                        <el-tooltip v-if="step2Data.cycle_rule.cycle_unit == 3" placement="right" effect="light">
                            <template #content>
                                <div class="tips_unit">
                                    当月执行的月份不存在选择的日期时，则在当月的最后一天执行。
                                    例如当周期频次设定为，每月31号10点时，那么6月执行的日期将在6月30号执行。
                                </div>
                            </template>
                            <el-icon>
                                <Warning />
                            </el-icon>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="周期执行" prop="cycle_rule.cycle_type">
                        <el-radio-group v-model="step2Data.cycle_rule.cycle_type">
                            <el-radio :label="1" value="1">未完成，继续分配</el-radio>
                            <el-radio :label="2" value="2">未完成，不分配</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>
            </template>
            <!-- 分配方式 -->
            <el-form-item v-if="step2Data.execution_mode == 1" label="分配方式" prop="cycle_rule.assign_mode">
                <el-radio-group v-model="step2Data.cycle_rule.assign_mode">
                    <el-radio :label="1" value="1">平均分配</el-radio>
                    <el-radio :label="2" value="2">随机分配</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <!--选择成员 -->
        <ZWDepart ref="DepartRef" :type="1" @submit="getDepart" />
        <!--选择线索 -->
        <ZWClues ref="ZWCluesRef" @submit="getCLues" />
        <!--选择客户 -->
        <ZWCustomer ref="ZWCustomerRef" @submit="getCust" />
    </el-card>
</template>

<script lang="ts" setup>
import UploadFile from './UploadFile.vue';
import { download, download2 } from '@/api/customer/clubManage/commonSea';

import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import ZWDepart from '@/components/ZWDepart.vue';

import ZWClues from '@/components/chart/ZWClues.vue';
import ZWCustomer from '@/components/chart/ZWCustomer.vue';

import upload from './upload.vue';
import { getSetionId, numFormat } from '@/utils/utils';
import { downloadCustTemplate } from '@/api/customerCenter/groupManage';
import { useRoute } from 'vue-router';
import router from '@/router';

const route = useRoute();
const step2Form = ref<any>(null);
const task_type = ref(1);
const step2Diabled = ref(false);
const step2 = ref(false);
const DepartRef = ref<any>(null);
const ZWCluesRef = ref<any>(null);
const ZWCustomerRef = ref<any>(null);

const ZWUploadRef = ref<any>(null);
const creators = ref([]);
const creators2 = ref([]);
const creators3 = ref([]);
const templateNum = ref(0);
const week = reactive(['一', '二', '三', '四', '五', '六', '日']);
const UploadFileRef = ref(null);
const UploadFileRef2 = ref(null);
const step2Data = reactive({
    checkList: [],
    work_user_type: 1,
    work_user_ids: [],
    execution_mode: 1, //外呼对象
    object_type: 2, // 对象类型/录入类型
    object_source: 1, // 选择/导入
    object_ids: [],
    import_file: '', // 上传文件xls
    import_id: '',
    entry_rule: {
        entry_day_switch: 2,
        entry_day_num: 5, //每日最少录入数量
        entry_user_switch: 2,
        entry_user_num: 20 //每个员工最少录入数量
    },
    cycle_rule: {
        assign_type: 1, //周期分配
        cycle_unit: 1,
        cycle_date: 1,
        cycle_time: '08:00',
        cycle_num: 5,
        cycle_type: 1, // 周期执行
        assign_mode: 1 //分配方式
    },
    cust_number: 0,
    clue_number: 0
});
const validCust = (rule: any, value: any, callback: any) => {
    const { object_type } = step2Data;

    if (value <= 0) {
        callback(new Error(`对象类型的${object_type == 1 ? '线索' : '客户'}不能为空`));
    } else {
        callback();
    }
};
const validCheck = (rule: any, value: any, callback: any) => {
    if (value.length <= 0) {
        callback(new Error('录入规则至少勾选一种'));
    } else if (value.length == 2) {
        if (step2Data.entry_rule.entry_user_num < step2Data.entry_rule.entry_day_num) {
            callback(new Error('每个员工至少录入数大于等于每日至少录入数'));
        } else {
            callback();
        }
    } else {
        callback();
    }
};
const validInputNum = (rule: any, value: any, callback: any) => {
    rule = /^[1-9]*$/;
    if (!rule.test(value)) {
        callback(new Error('数字输入框值必须大于0'));
    } else {
        callback();
    }
};
const step2Rules = reactive<FormRules>({
    work_user_type: { required: true, message: '执行员工至少选一个', trigger: 'blur' },
    work_user_ids: { required: true, message: '指定员工不能为空', trigger: 'blur' },
    object_type: { required: true, message: '对象类型至少选一个', trigger: 'blur' },
    object_source: { required: true, message: '选择至少选一个', trigger: 'blur' },
    execution_mode: { required: true, message: '外呼对象选择至少选一个', trigger: 'blur' },
    clue_number: { required: true, validator: validCust, trigger: ['blur', 'change'] },
    cust_number: { required: true, validator: validCust, trigger: ['blur', 'change'] },
    checkList: { required: true, validator: validCheck, trigger: ['blur', 'change'] },
    cycle_rule: {
        assign_mode: { required: true, message: '分配方式选择至少选一个', trigger: 'blur' },
        assign_type: { required: true, message: '分配规则选择至少选一个', trigger: 'blur' },
        cycle_type: { required: true, message: '周期执行选择至少选一个', trigger: 'blur' },
        cycle_unit: { required: true, message: '周期频次选择至少选一个', trigger: 'blur' }
    },
    entry_rule: {
        entry_day_num: { required: true, validator: validInputNum, trigger: 'blur' },
        entry_user_num: { required: true, validator: validInputNum, trigger: 'blur' }
    }
});
// 多选
const changeCheckbox = (val: any) => {
    if (val.length == 1) {
        if (val[0] == 'entry_day_switch') {
            step2Data.entry_rule.entry_day_switch = 1;
            step2Data.entry_rule.entry_user_switch = 2;
        } else {
            step2Data.entry_rule.entry_day_switch = 2;
            step2Data.entry_rule.entry_user_switch = 1;
        }
    } else if (val.length == 2) {
        step2Data.entry_rule.entry_day_switch = 1;
        step2Data.entry_rule.entry_user_switch = 1;
    } else {
        step2Data.entry_rule.entry_day_switch = 2;
        step2Data.entry_rule.entry_user_switch = 2;
    }
};
//切换外呼对象
const changeMode = () => {
    if (step2Data.execution_mode == 1) {
        step2Data.object_source = 1;
    }
};
const changeSource = (val: any) => {
    step2Data.cust_number = 0;
    if (val == 2) creators2.value = [];
    ZWCustomerRef.value.echoDataId = creators2.value;
};
// 上传文件
const uploadFile = async (file: any) => {
    step2Data.import_id = file.import_id;
    step2Data.cust_number = file.count;
};
//打开使用成员弹框
const openDepart = () => {
    DepartRef.value.appDialog.title = '选择员工';
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = creators.value;
};
// 获取使用成员
const getDepart = (res: any) => {
    creators.value = res;
    DepartRef.value.departVisble = false;
    step2Data.work_user_ids = getSetionId('id', creators.value);
    step2Form.value.validateField('work_user_ids');
};
//打开选择客户弹框
const openCustomer = () => {
    ZWCustomerRef.value.appDialog.title = '选择客户';
    ZWCustomerRef.value.appDialog.visible = true;
    ZWCustomerRef.value.echoDataId = step2Data.object_ids;
};

//打开选择线索弹框
const openClues = () => {
    ZWCluesRef.value.appDialog.title = '选择线索';
    ZWCluesRef.value.appDialog.visible = true;
    ZWCluesRef.value.echoDataId = step2Data.object_ids;
};

// 获取选择线索
const getCLues = (res: any) => {
    step2Data.clue_number = res.length;
    creators3.value = res;
    step2Data.object_ids = getSetionId('id', res);
};

// 获取选择客户
const getCust = (res: any) => {
    creators2.value = res;
    step2Data.cust_number = res.length;
    ZWCustomerRef.value.departVisble = false;
    step2Data.object_ids = getSetionId('id', creators2.value);
};

// 删除
const removeDepart = (key: number) => {
    const arr = creators.value.find((item: any) => item.id == key);
    creators.value = creators.value.filter((item: any) => item.id !== key);
    DepartRef.value.removeItem(arr);
    step2Data.work_user_ids = getSetionId('id', creators.value);
};
// 下载模板
const downTemplate = () => {
    downloadCustTemplate().then((res: any) => {
        window.open(res.file_url);
    });
};
// 下一步
const save = async () => {
    if (step2Data.execution_mode == 2) {
        delete step2Data.object_source;
        delete step2Data.object_ids;
    }
    step2.value = await step2Form.value.validate();
};
const changeAssignType = (val: number) => {
    if (val == 2) {
        step2Data.cycle_rule.cycle_time = '08:00';
        step2Data.cycle_rule.cycle_num = 5;
        step2Data.cycle_rule.cycle_date = 1;
        step2Data.cycle_rule.cycle_unit = 1;
    }
};
const cycleUnit = (val: number) => {
    step2Data.cycle_rule.cycle_date = 1;
};
// 优化
const fileType = ref('');
const fileInfo = ref<any>({
    name: '',
    code: '',
    url: ''
});
// 获取上传文件
const getFile = (v: any) => {
    const { object_type } = step2Data;
    fileInfo.value = v;
    step2Data.import_id = v.import_id;
    if (object_type == 1) step2Data.clue_number = v.count;
    else step2Data.cust_number = v.count;
};
const onDeleteFile = () => {
    if (step2Diabled.value) return;
    fileInfo.value = {};
    step2Data.import_id = '';
};
const onDownload = (v: any) => {
    switch (+v) {
        case 3:
        case 4:
            download({ type: v == 3 ? 1 : 2 }).then((res: any) => {
                window.location = res.file_url;
            });
            break;
        case 1:
        case 2:
            download2({ type: v == 1 ? 1 : 2 }).then((res: any) => {
                window.location = res.file_url;
            });
            break;
    }
};
const changeType = () => {
    step2Data.import_file = '';
    step2Data.import_id = '';
    step2Data.object_source = 1;
    step2Data.clue_number = 0;
    step2Data.cust_number = 0;
    UploadFileRef.value.uploadFileList = [];
    UploadFileRef2.value.uploadFileList = [];
};
onMounted(() => {
    task_type.value = router.currentRoute.value.query?.val;
});

watch(
    () => step2Data.cust_number,
    val => {
        if (val > 0) step2Form.value.validateField('cust_number');
    }
);
defineExpose({
    creators,
    save,
    fileInfo,
    step2Diabled,
    step2Data,
    creators3,
    step2
});
</script>
<style lang="scss" scoped>
.box-card {
    border-bottom: none;
    min-height: calc(100vh - 294px);
}

:deep(.el-form-item) {
    margin-bottom: 0;

    .el-radio-group {
        height: 38px;
    }
}

.mr5 {
    margin-right: 5px;
}

.mb0 {
    margin-bottom: 0;
}

.mar_w {
    width: 140px;
    margin: 0 5px;
}

.rule_checkbox {
    display: block;
    margin-bottom: 10px;
}

.tips_unit {
    width: 220px;
    font-size: 12px;
    font-family: PingFangSC-Regular, 'PingFang SC';
    font-weight: 400;
    color: #33302d;
    line-height: 20px;
}

.title {
    font-size: 16px;
    font-family: PingFangSC-Medium, 'PingFang SC';
    font-weight: 500;
    color: #585858;
    line-height: 22px;
}

.user_list {
    width: 580px;

    .user_item_tag {
        margin-right: 10px;
        margin-bottom: 5px;

        .tag_icon {
            width: 15px;
            height: 15px;
            margin-right: 5px;
            vertical-align: middle;
        }
    }
}

.clues_box {
    :deep(.el-tabs) {
        width: 660px;
        border-radius: 4px;
        border: 1px solid #eaeaea;
        min-height: 163px;

        .el-tabs__header {
            .el-tabs__nav-scroll {
                margin-left: 20px;

                .el-tabs__item {
                    height: 44px;
                    line-height: 44px;
                }
            }
        }

        .el-tabs__content {
            margin: 25px;
        }
    }

    .import_box {
        position: relative;

        .template_box {
            position: absolute;
            left: 110px;
            top: 1px;
        }
    }

    .cust_number {
        margin-top: 10px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #33302d;

        span {
            color: #ff6b00;
            margin: 0 5px;
        }
    }
}

.check_dom {
    display: block;
    margin-bottom: 15px;
}

.line {
    margin: 20px 0;
}

.contract_code {
    display: flex;
    margin-bottom: 16px;

    .btn {
        margin-left: 16px;

        &_down {
            border: none;
            color: #ff6b00;
        }
    }
}

.contract_show {
    width: 440px;
    height: 32px;
    padding: 0 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f2f2f2;

    .contract_show_left {
        display: flex;
        align-items: center;

        .contract_show_img {
            width: 20px;
            height: 20px;
            margin-right: 5px;
        }
    }

    .contract_show_delete {
        cursor: pointer;

        &:hover {
            color: red;
        }
    }
}
</style>
